﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Web.CrmContacto.Code;
using CrmContacto.Contracts;
using CrmContacto.Contracts.Contracts.Search;
using Web.Framework;
using CrmContacto.WebApp.Code.InnerClasses;
using Web.Framework.Translate;
using CrmContacto.Contracts.Contracts;
using Web.Framework.Mapper;
using Web.CrmContacto.Code.Security;
using Web.Framework.Helpers;

namespace CrmContacto.WebApp.App
{
    public partial class PuntoDeVentaEdit : BasePage
    {
        public PuntoDeVenta ptoDeVentaCurrent
        {
            get
            {
                return (PuntoDeVenta)ViewState["ptoDeVentaCurrent"];
            }
            set
            {
                ViewState["ptoDeVentaCurrent"] = value;
            }
        }

        private List<LinkButton> actionButtons = new List<LinkButton>();
        LinkButton eliminarButton = new LinkButton();
        LinkButton activarInactivarButton = new LinkButton();
        LinkButton guardarButton = new LinkButton();
        LinkButton nuevoSubPtoButton = new LinkButton();
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            guardarButton.ID = "BoCommandGuardar";
            guardarButton.Text = LocalizationProvider.Instance["Bo.Command.Guardar"];
            guardarButton.Click += new EventHandler(lnkGuardar_Click);
            actionButtons.Add(guardarButton);

            LinkButton volverButton = new LinkButton();
            SetJavascriptForClientClickDirtyChech(volverButton);
            volverButton.CausesValidation = false;
            volverButton.ID = "BoCommandVolver";
            volverButton.Text = LocalizationProvider.Instance["Bo.Command.Volver"];
            volverButton.Click += new EventHandler(lnkCancelar_Click);
            actionButtons.Add(volverButton);

            eliminarButton.ID = "BoCommandEliminar";
            eliminarButton.CausesValidation = false;
            eliminarButton.Text = LocalizationProvider.Instance["Bo.Command.Eliminar"];
            eliminarButton.Click += new EventHandler(eliminarButton_Click);
            actionButtons.Add(eliminarButton);

            activarInactivarButton.ID = "BoCommandActivar";
            activarInactivarButton.CausesValidation = false;
            SetJavascriptForClientClickDirtyChech(activarInactivarButton);
            activarInactivarButton.Click += new EventHandler(ActivarInactivarButton_Click);
            actionButtons.Add(activarInactivarButton);

            nuevoSubPtoButton.ID = "BoCategoriasActionMenuSubPtoVta";
            nuevoSubPtoButton.Text = LocalizationProvider.Instance["Bo.SubPuntoDeVenta.ActionMenu.Nuevo"];
            nuevoSubPtoButton.Click += new EventHandler(nuevoSubPtoButton_Click);
            actionButtons.Add(nuevoSubPtoButton);

            base.LoadContextActions(actionButtons);
        }

        private void nuevoSubPtoButton_Click(object sender, EventArgs e)
        {
            try
            {
                Response.Redirect(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlSubPuntoDeVentaEdit + string.Format("?pdvId={0}", ptoDeVentaCurrent.Id), true);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void ActivarInactivarButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (ptoDeVentaCurrent.Id != 0)
                {
                    int estado = ptoDeVentaCurrent.Activo ? 0 : 1;
                    WebServiceHelper.ActivarEntidad(ptoDeVentaCurrent.GetType().Name, estado, ptoDeVentaCurrent.Id);
                    ptoDeVentaCurrent.Activo = estado == 1;
                    Bind();
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void eliminarButton_Click(object sender, EventArgs e)
        {
            try
            {
                WebServiceHelper.EliminarPuntoDeVentaDto(ptoDeVentaCurrent.Id);
                Response.Redirect(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlPuntoDeVentaList + string.Format("?{0}=1", MiscClass.QueryShowDeleted), true);
                //NuevoPuntoDeVenta();
                //Bind();
                //this.masterPage.ShowMessage(LocalizationProvider.Instance["Bo.Message.RegistroEliminado"], WebMessageType.Notification);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {

            try
            {
                HasPermissionToSeeMe(CrmSecurity.PDV_MANAGE, CrmSecurity.PDV_SEARCH);

                if (!this.IsPostBack)
                {
                    if (this.Request.QueryString["Id"] == null)
                    {
                        NuevoPuntoDeVenta();
                    }
                    else
                    {
                        var search = new PuntoDeVentaSearch() { PuntoDeVentaId = Convert.ToInt32(this.Request.QueryString["Id"]), LoadSubPuntos = true };
                        search.EmpresaId = BasePage.CompanyId;
                        ptoDeVentaCurrent = WebServiceHelper.GetPuntoDeVentaDto(search).First();

                    }

                    Bind();
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void NuevoPuntoDeVenta()
        {
            ptoDeVentaCurrent = new PuntoDeVenta();
            ptoDeVentaCurrent.EmpresaId = BasePage.CompanyId;
            ptoDeVentaCurrent.Activo = true;
        }

        protected override void ApplySecurity()
        {
            base.ApplySecurity();

            if (ptoDeVentaCurrent.Id != 0)
            {
                SetJavascriptForDeleteRecord(eliminarButton, ptoDeVentaCurrent.Nombre);
                eliminarButton.Visible =
                activarInactivarButton.Visible =
                lnkGuardar.Visible =
                guardarButton.Visible = HasPermissionFor(CrmSecurity.PDV_MANAGE);
            }
            else
            {
                lnkGuardar.Visible =
                guardarButton.Visible = HasPermissionFor(CrmSecurity.PDV_MANAGE);
                eliminarButton.Visible = false;
                activarInactivarButton.Visible = false;
            }

            if (this.Grid.DataSource != null)
            {
                this.Grid.Columns[0].Visible = HasPermissionFor(CrmSecurity.PDV_MANAGE) || HasPermissionFor(CrmSecurity.PDV_SEARCH);
                this.Grid.Columns[1].Visible = HasPermissionFor(CrmSecurity.PDV_MANAGE);
            }
        }

        private void Bind()
        {
            EntityMapper.Map(ptoDeVentaCurrent, this);

            BindGrid();

            this.lblActivo.Text = ptoDeVentaCurrent.Activo ? LocalizationProvider.Instance["EstadoCliente.Activo"] : LocalizationProvider.Instance["EstadoCliente.Inactivo"];

            if (ptoDeVentaCurrent.Id != 0)
            {
                if (ptoDeVentaCurrent.Activo)
                {
                    activarInactivarButton.Text = LocalizationProvider.Instance["Bo.Command.Inactivar"];
                }
                else
                {
                    activarInactivarButton.Text = LocalizationProvider.Instance["Bo.Command.Activar"];
                }
            }
        }

        private void BindGrid()
        {
            this.Grid.DataSource = ptoDeVentaCurrent.SubPuntosDeVenta;
            this.Grid.DataBind();
        }

        private void SetData()
        {
            EntityMapper.Map(this, ptoDeVentaCurrent);
        }

        private void Save()
        {
            ptoDeVentaCurrent = WebServiceHelper.SavePuntoDeVentaDto(ptoDeVentaCurrent);
        }       

        protected void lnkGuardar_Click(object sender, EventArgs e)
        {
            try
            {               
                SetData();
                Save();

                // Limpio el cache
                ClearPuntosDeVenta(HttpContext.Current);

                Response.Redirect(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlPuntoDeVentaList + string.Format("?{0}=1", MiscClass.QueryShowSaveOk), true);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkCancelar_Click(object sender, EventArgs e)
        {
            try
            {
                Response.Redirect(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlPuntoDeVentaList, true);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void Grid_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "editar")
                {
                    int subPuntoDeVentaId = Convert.ToInt32(this.Grid.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    this.Response.Redirect(string.Format(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlSubPuntoDeVentaEdit + "?Id={0}&pdvId={1}", subPuntoDeVentaId, ptoDeVentaCurrent.Id), true);
                }
                else if (e.CommandName == "eliminar")
                {
                    int subPuntoDeVentaId = Convert.ToInt32(this.Grid.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    WebServiceHelper.RemoveSubPuntoDeVentaFromPdv(subPuntoDeVentaId);
                    var camp = ptoDeVentaCurrent.SubPuntosDeVenta.Where(i => i.Id == subPuntoDeVentaId).Single();
                    ptoDeVentaCurrent.SubPuntosDeVenta.Remove(camp);
                    Bind();
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    e.Row.Cells[0].Attributes.Add("title", "Editar");
                    e.Row.Cells[1].Attributes.Add("title", "Eliminar");
                    ImageButton btnEliminarCtrl = (ImageButton)e.Row.FindControl("btnEliminar");
                    SetJavascriptForDeleteRecord(btnEliminarCtrl, ((SubPuntoDeVenta)e.Row.DataItem).Codigo);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkExportarAExcel_Click(object sender, EventArgs e)
        {
            try
            {
                bool previousAllowPaging = this.Grid.AllowPaging;
                this.Grid.AllowPaging = false;

                BindGrid();

                GridViewExportExcelUtil.Export("PuntosDeVenta.xls", this.Grid, 0, 1);

                this.Grid.AllowPaging = previousAllowPaging;
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }
    }
}